package kz.simplex.photobox.action;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import kz.simplex.photobox.model.User;
import kz.simplex.photobox.util.HashUtils;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

@Stateless
@Name("authenticator")
public class AuthenticatorBean implements Authenticator
{
    @Logger 
    private Log log;

    @In 
    Identity identity;
    
    @In
    Credentials credentials;
    
    @In
    EntityManager entityManager;
        
    @Out(required=false, scope=ScopeType.SESSION)
    private UserHome userHome;
    

    public boolean authenticate()
    {
        log.info("authenticating {0}", credentials.getUsername());
        
        try {
        	
        	User user = (User)entityManager.createQuery("from User where username = :username and password = :password")
        							.setParameter("username", credentials.getUsername())
        							.setParameter("password", HashUtils.hash(credentials.getPassword()))
        							.getSingleResult();
        	
        	if (userHome == null) {
        		userHome = new UserHome();
        	}
        	userHome.setInstance(user);
        	identity.addRole(user.getRole().getTitle());
        	return true;
        	
        } catch(NoResultException e) {
        	return false;
        }
    }
}
